package com.jixuian.rabbitmq.sender;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jixuian.rabbitmq.po.TransMessagePO;
import com.jixuian.rabbitmq.service.TransMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class TransMessageSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private TransMessageService transMessageService;

    public void send(String exchange, String routingKey, String payload) {
        log.info("send(), exchange:{}, routingKey:{}, payload:{}", exchange, routingKey, payload);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String payloadStr = objectMapper.writeValueAsString(payload);
            TransMessagePO transMessagePO = transMessageService.messageSendReady(exchange, routingKey, payloadStr);

            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setContentType("application/json");
            messageProperties.setMessageId(transMessagePO.getId());

            Message message = new Message(payloadStr.getBytes(), messageProperties);
            // 把消息持久化的id放入CorrelationData, 消息返回时会带回
            rabbitTemplate.convertAndSend(exchange, routingKey, message, new CorrelationData(transMessagePO.getId()));

            log.info("message sent, ID:{}", transMessagePO.getId());
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
    }
}
